define([ 'angular','filters'], function(angular) {
'use strict';
	angular.module('sale.saleOrderSingle', ['app.filters'])

	.controller('saleOrderSingleCtrl'
			,['$rootScope', '$scope','systemService', '$http'
			  , 'uServiceCenter' ,'BizData', 'apiService'
			   , f])//控制器结束
	function f($rootScope,$scope,systemService, $http
					   , uServiceCenter, BizData, apiService
					   ) {
		
		var common = require('common');
		
		//test
		$scope.today = function() {
		    $scope.dt = new Date();
		  };
		  $scope.today();

		  $scope.clear = function() {
		    $scope.dt = null;
		  };

		  $scope.inlineOptions = {
		    customClass: getDayClass,
		    minDate: new Date(),
		    showWeeks: true
		  };

		  $scope.dateOptions = {
		    dateDisabled: disabled,
		    formatYear: 'yy',
		    maxDate: new Date(2020, 5, 22),
		    minDate: new Date(),
		    startingDay: 1
		  };

		  // Disable weekend selection
		  function disabled(data) {
		    var date = data.date,
		      mode = data.mode;
		    return mode === 'day' && (date.getDay() === 0 || date.getDay() === 6);
		  }

		  $scope.toggleMin = function() {
		    $scope.inlineOptions.minDate = $scope.inlineOptions.minDate ? null : new Date();
		    $scope.dateOptions.minDate = $scope.inlineOptions.minDate;
		  };

		  $scope.toggleMin();

		  $scope.open1 = function() {
		    $scope.popup1.opened = true;
		  };

		  $scope.open2 = function() {
		    $scope.popup2.opened = true;
		  };

		  $scope.setDate = function(year, month, day) {
		    $scope.dt = new Date(year, month, day);
		  };

		  $scope.formats = ['yyyy-MM-dd', 'dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
		  $scope.format = $scope.formats[0];
		  $scope.altInputFormats = ['M!/d!/yyyy'];

		  $scope.popup1 = {
		    opened: false
		  };

		  $scope.popup2 = {
		    opened: false
		  };

		  var tomorrow = new Date();
		  tomorrow.setDate(tomorrow.getDate() + 1);
		  var afterTomorrow = new Date();
		  afterTomorrow.setDate(tomorrow.getDate() + 1);
		  $scope.events = [
		    {
		      date: tomorrow,
		      status: 'full'
		    },
		    {
		      date: afterTomorrow,
		      status: 'partially'
		    }
		  ];

		  function getDayClass(data) {
		    var date = data.date,
		      mode = data.mode;
		    if (mode === 'day') {
		      var dayToCheck = new Date(date).setHours(0,0,0,0);
		      console.log('dayToCheck-->>',dayToCheck);

		      for (var i = 0; i < $scope.events.length; i++) {
		        var currentDay = new Date($scope.events[i].date).setHours(0,0,0,0);
console.log('currentDay-->>',currentDay);
		        if (dayToCheck === currentDay) {
		          return $scope.events[i].status;
		        }
		      }
		    }

		    return '';
		  }
		  
		  
		  
		  
		
		var Model = this;
//		$scope.path = $rootScope.path;
//		$scope.createPermission = $rootScope.path + ':create';
//		console.log('窗口打开时的参数1-->',$rootScope.winParams);
		
		Model.ngChange = function(event){
			console.log('event-->>',event);
		};
		
		//定义页面级别的变量
		var systemCode = $rootScope.winid; //系统代码

		var flowType = 0;
		var billTypeName = "";
		
		var origin = 'SGLR';
		var originName = '手工录入';

		var autoCode; //是否自动编码
		var revOpay; //入库出库
		var costingCode; //影响成本码
		var storageTypeD ;
		var storageTypeDLabel ;
		var storageType ;
		var storageTypeLabel ;

		var floorNo;
		//var floorNoD;

		/////////////////////////////////////////////////////////////////////////////////////////////////

		var billType = 'XSDD';
		var direction;
//		var departmentNo;
//		var departmentName;
		var employeeNo;
		var employeeName;
		//var targetNo;
		//var targetName;

		var orderNo;
		var maxDetailNo;
		var serialNo;
		var storageNo;
		var storageName;

		var factoryID;
		var factoryNo;
		var factoryName;
		
		var billNo;

		var state;
		var status;
		var audit;
		var orderDate;
		
		var userId;
		var enterpriseNo;
		var enterpriseName;
		
		var taxType;
		var taxTypeLabel;
		var taxRate;
		
		var customerID;
		var customerNo;
		var shortName
		var customerName;
		
		/**
		name:bizData#onNewCreateParam
		description: <b>[回调型事件]</b>业务新增数据创建新增参数事件，可以增加和修改用户自定义的参数
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"param" : {justep.Request.ActionParam} 新增参数对象,
			"defaultValues" : array - 新增行的默认值数组 ，数组的长度决定新增行数，数组中的对象是列的默认值
				defaultValues格式：
					[
						{列名:默认值,...},
						{列名:默认值,...},
						...
					]
		}
		</xmp>	
		@see justep.XData#newData
		@see justep.Request.ActionParam
		*/
		Model.dataMasterNewCreateParam = function(event) {
			event.param = {"billType": billType};
		}
		
		/**
		name:bizData#onBeforeNew
		description: <b>[回调型事件]</b>业务数据新增前
		@param {object} event 它的结构如下:<br/>{"source":组件的js对象,"cancel":可修改，设置为true后中断当前new动作}
		 */
		Model.dataMasterBeforeNew = function(event) {

		};
		/**
		 * name:bizData#onAfterNew description: <b>[回调型事件]</b>业务数据新增后
		 * 
		 * @param event
		 *            它的结构如下:<br/>{"source":组件的js对象,"id":新增的行Id}
		 */
		Model.dataMasterAfterNew = function(event){
			//创建行后赋值
			event.source.setValue('systemCode',systemCode,event.id);
			
			event.source.setValue('storageTypeD', 'cus', event.id);	
			event.source.setValue('storageTypeDLabel', '客户', event.id);	
			event.source.setValue('storageType', 'chc', event.id);	
			event.source.setValue('storageTypeLabel', '存货仓', event.id);	
			
			//产生自动流水号
			//获取初始化参数
			//获取单据参数
			var enterpriseNo = event.source.getValue("enterpriseNo", event.id);
			if(billType && enterpriseNo){
				var options = {};
				options.billType = billType;
				options.ognID = enterpriseNo;
				options.async = false;
				var billParam = systemService.getBillParam(options);
				
				if (billParam.state == "success"){
					event.source.setValue('dealType',billParam.dealType,event.id);
					event.source.setValue('billTypeName',billParam.billTypeName,event.id);
					event.source.setValue('flowType',billParam.flowType,event.id);
					event.source.setValue('origin', billParam.origin, event.id);	
					event.source.setValue('originName', billParam.originName, event.id);	
					//event.source.setValue('revOpay', billParam.revOpay, event.id);	
					//event.source.setValue('direction', billParam.direction, event.id);
					//event.source.setValue('costingCode', billParam.costingCode, event.id);	
					
					if (billParam.autoCode = "Y"){
						//产生自动流水号
						event.source.setValue('orderNo',billParam.billNo,event.id);
					}
				}else{
					systemService.dialogMsg('请在单据设置中进行初始化。');
				}
			}

		};

		/**
		name:bizData#onBeforeDelete
		description: <b>[回调型事件]</b>业务数据删除前
		@param {object} event 它的结构如下:<br/>
		{
			"source":组件的js对象
			,"cancel":可修改	，设置为true后中断当前delete动作
			,"deleteIDList":删除的行Id数组
		}
		*/
		Model.dataMasterBeforeDelete = function(event) {
//			alert(event.deleteIDList[0]);
		}
		
		/**
		name:bizData#onAfterDelete
		description: <b>[回调型事件]</b>业务数据删除后
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"deleteIDList" : 删除的行Id数组
		}
		</xmp>	
		*/
		Model.dataMasterAfterDelete = function(event) {
//			alert('删除之后！')
		}

		
		
		/**
		name:bizData#onIndexChanged
		description: <b>[回调型事件]</b>行记录变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"rowID" : 行Id,
			"rowIndex" : 行索引
		}
		</xmp>	
		*/
		Model.dataMasterIndexChanged = function(event) {
			if(event.rowID!=null){
				Model.dataDetail.fMasterID = event.rowID;
	       		Model.dataDetail.refreshData();
			}else{
				Model.dataDetail.clearData();
			}
		}
		
		/**
		name:bizData#onDataChanged
		description: <b>[回调型事件]</b>数据发生变化（包括新增、刷新、删除、修改引起的变化），感知从data的变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"changedSource" ：触发变化的组件的js对象，当从data触发时返回从data对象,
			"selfChanged" : 是否自身变化，false：从data触发的变化,
			"type" : 触发变化的类型，包括：new、delete、refresh、valueChanged、clear，其他参数根据触发类型不同给出不同参数，参考onAfterNew等事件参数
		}
		</xmp>	
		*/
		Model.dataMasterDataChanged = function(event) {
			
		}
		
		Model.dataMasterValueChanging = function(event) {
			console.log('dataMasterValueChanging-->',event);
			//event.value = 'liushupeng';
		};
		
		/**
		name:bizData#onValueChanged
		description: <b>[回调型事件]</b>数据变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"column" : 关系,
			"rowIndex" : 行索引,
			"value" : 新值,
			"originalValue" : 旧值
		}
		</xmp>	
		*/
		//输入值变化，监视input的输入，ng-change
		Model.dataMasterValueChanged = function(event) {
			uServiceCenter.orderMasterValueChanged(event);
			if(event.column=='customerNo'){
				var rowID = event.source.getID(event.rowIndex);
				var storageTypeD = event.source.getValue('storageTypeD',rowID);
				var storageTypeDLabel = event.source.getValue('storageTypeDLabel',rowID);
				var customerID = event.source.getValue('customerID',rowID);
				var customerNo = event.source.getValue('customerNo',rowID);
				var shortName = event.source.getValue('shortName',rowID);
				var customerName = event.source.getValue('customerName',rowID);
				var dataDetail = Model.dataDetail;
				for(var i=0;i<dataDetail.getCount();i++){
					dataDetail.setValue('storageTypeD',storageTypeD,dataDetail.getID(i));
					dataDetail.setValue('storageTypeDLabel',storageTypeDLabel,dataDetail.getID(i));
					dataDetail.setValue('customerID',customerID,dataDetail.getID(i));
					dataDetail.setValue('customerNo',customerNo,dataDetail.getID(i));
					dataDetail.setValue('shortName',shortName,dataDetail.getID(i));
					dataDetail.setValue('customerName',customerName,dataDetail.getID(i));
				}
			}
		};
		
		
		Model.dataMasterBeforeSave = function(event) {
//			console.log('dataMasterBeforeSave-->',event);
		};
		
		
		Model.dataMasterAfterSave = function(event) {
//			console.log('dataMasterAfterSave-->',event);
		}
		

		
		
		
		
		

		/**
		name:bizData#onBeforeDelete
		description: <b>[回调型事件]</b>业务数据删除前
		@param {object} event 它的结构如下:<br/>
		{
			"source":组件的js对象
			,"cancel":可修改	，设置为true后中断当前delete动作
			,"deleteIDList":删除的行Id数组
		}
		*/
		Model.dataDetailBeforeDelete = function(event) {
			console.log('dataDetailBeforeDelete-->',event);
		}
		/**
		name:bizData#onAfterDelete
		description: <b>[回调型事件]</b>业务数据删除后
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"deleteIDList" : 删除的行Id数组
		}
		</xmp>	
		*/
		Model.dataDetailAfterDelete = function(event) {
			console.log('dataDetailAfterDelete-->',event);
			uServiceCenter.orderDetailAfterDelete(event);
			
			/*
			var dataMaster = Model.dataMaster;
			var masterRowID = dataMaster.getCurrentID();

			//更新主表中子表记录数
			dataMaster.setValue('detailsCount', dataMaster.getValue('detailsCount', masterRowID) - 1, masterRowID);	
			
			//计算主表合计
			//数量
			var column="itemAmount";
			var sum = event.source.getSum(column);
			dataMaster.setValue(column,sum,masterRowID);
			//金额
			column="orderAmount";
			sum = event.source.getSum(column);
			dataMaster.setValue(column,sum,masterRowID);
			//未税金额
			column="orderAmountOld";
			sum = event.source.getSum(column);
			dataMaster.setValue(column,sum,masterRowID);
			//税额
			column="orderAmountTax";
			sum = event.source.getSum(column);
			dataMaster.setValue(column,sum,masterRowID);
			//加税合计
			column="orderAmountTotal";
			sum = event.source.getSum(column);
			dataMaster.setValue(column,sum,masterRowID);
			//件数
			column="pieceQuantity";
			sum = event.source.getSum(column);
			dataMaster.setValue(column,sum,masterRowID);
			//包装重量
			column="orderWeight";
			sum = event.source.getSum(column);
			dataMaster.setValue(column,sum,masterRowID);
			//运费
			column="freightAmount";
			sum = event.source.getSum(column);
			dataMaster.setValue(column,sum,masterRowID);
			//其他费用
			column="apportionAmount";
			sum = event.source.getSum(column);
			dataMaster.setValue(column,sum,masterRowID);
*/
		}
		
		
		
		/**
		name:bizData#onIndexChanged
		description: <b>[回调型事件]</b>行记录变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"rowID" : 行Id,
			"rowIndex" : 行索引
		}
		</xmp>	
		*/
		Model.dataDetailIndexChanged = function(event) {
			console.log('dataDetailIndexChanged-->',event);
		}
		
		/**
		name:bizData#onDataChanged
		description: <b>[回调型事件]</b>数据发生变化（包括新增、刷新、删除、修改引起的变化），感知从data的变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"changedSource" ：触发变化的组件的js对象，当从data触发时返回从data对象,
			"selfChanged" : 是否自身变化，false：从data触发的变化,
			"type" : 触发变化的类型，包括：new、delete、refresh、valueChanged、clear，其他参数根据触发类型不同给出不同参数，参考onAfterNew等事件参数
		}
		</xmp>	
		*/
		Model.dataDetailDataChanged = function(event) {
			console.log('dataDetailDataChanged-->',event);
		}
		
		/**
		name:bizData#onValueChanged
		description: <b>[回调型事件]</b>数据变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"column" : 关系,
			"rowIndex" : 行索引,
			"value" : 新值,
			"originalValue" : 旧值
		}
		</xmp>	
		*/
		//输入值变化，监视input的输入，ng-change
		Model.dataDetailValueChanged = function(event) {
			console.log('dataDetailValueChanged-->',event);
			uServiceCenter.orderCalculate(event);
		}
		

		/**
		name:bizData#onBeforeNew
		description: <b>[回调型事件]</b>业务数据新增前
		@param {object} event 它的结构如下:<br/>{"source":组件的js对象,"cancel":可修改，设置为true后中断当前new动作}
		 */
		Model.dataDetailBeforeNew = function(event) {
			console.log('dataDetailBeforeNew-->',event);
			// 明细数据新增之前
			// 检查主表中的数据是否完整
			var dataMaster = Model.dataMaster;
			var rowID = dataMaster.getCurrentID();
			
			state = dataMaster.getValue('state', rowID);
			status = dataMaster.getValue('status', rowID);
			audit = dataMaster.getValue('audit', rowID);
			orderDate = dataMaster.getValue('orderDate', rowID);
			
			//////////////////////////////////////////////////////////////////////
			systemCode = dataMaster.getValue('systemCode', rowID);
//			costingCode = dataMaster.getValue('costingCode', rowID);
			storageTypeD = dataMaster.getValue('storageTypeD', rowID);
			storageTypeDLabel = dataMaster.getValue('storageTypeDLabel', rowID);
			storageType = dataMaster.getValue('storageType', rowID);
			storageTypeLabel = dataMaster.getValue('storageTypeLabel', rowID);

			//////////////////////////////////////////////////////////////////////

			// 判断如果那些为空，则拒绝新增明细数据
			factoryID = dataMaster.getValue('factoryID', rowID);
			factoryNo = dataMaster.getValue('factoryNo', rowID);
			factoryName = dataMaster.getValue('factoryName', rowID);
			if (factoryNo == null || factoryNo == "") {
				// 取消新增操作
//				alert('工厂不能为空！请先选择主表中的工厂，然后再在明细表中新增行。');
				event.cancel = true;
				systemService.dialogMsg('工厂不能为空！请先选择主表中的工厂，然后再在明细表中新增行。');
				
			}	
			// 判断如果那些为空，则拒绝新增明细数据
			customerID = dataMaster.getValue('customerID', rowID);
			customerNo = dataMaster.getValue('customerNo', rowID);
			shortName = dataMaster.getValue('shortName', rowID);
			customerName = dataMaster.getValue('customerName', rowID);
			if (customerNo == null || customerNo == "") {
				// 取消新增操作
//				alert('出入库部门不能为空！请先选择主表中的出入库部门，然后再在明细表中新增行。')
				event.cancel = true;
				systemService.dialogMsg('客户不能为空！请先选择主表中的客户，然后再在明细表中新增行。');
			}

			billType = dataMaster.getValue('billType', rowID);
//			direction = dataMaster.getValue('direction', rowID);
//			departmentNo = dataMaster.getValue('departmentNo', rowID);
//			departmentName = dataMaster.getValue('departmentName', rowID);
			employeeNo = dataMaster.getValue('employeeNo', rowID);
			employeeName = dataMaster.getValue('employeeName', rowID);
//			targetNo = dataMaster.getValue('targetNo', rowID);
//			targetName = dataMaster.getValue('targetName', rowID);

			orderNo = dataMaster.getValue('orderNo', rowID);
			
			//处理从表流水号
			maxDetailNo=dataMaster.getValue('maxDetailNo', rowID);
			maxDetailNo++;
			var detailNo=common.preZeroFill(maxDetailNo, 5);
			serialNo=detailNo;
				
			billTypeName = dataMaster.getValue('billTypeName', rowID);
			
			//////////////////////////////////////////////////////////////////////
//			revOpay = dataMaster.getValue('revOpay', rowID);
			//////////////////////////////////////////////////////////////////////
			
			taxType = dataMaster.getValue('taxType', rowID);
			taxTypeLabel = dataMaster.getValue('taxTypeLabel', rowID);
			taxRate = dataMaster.getValue('taxRate', rowID);
			
			userId = dataMaster.getValue('userId', rowID);
			enterpriseNo = dataMaster.getValue('enterpriseNo', rowID);
			enterpriseName = dataMaster.getValue('enterpriseName', rowID);

		};
		/**
		 * name:bizData#onAfterNew description: <b>[回调型事件]</b>业务数据新增后
		 * 
		 * @param event
		 *            它的结构如下:<br/>{"source":组件的js对象,"id":新增的行Id}
		 */
		Model.dataDetailAfterNew = function(event){
			console.log('dataDetailAfterNew-->',event);
			var dataDetail = event.source;
			var rowID = event.id;

			dataDetail.setValue('state', state, rowID);
			dataDetail.setValue('status', status, rowID);
			dataDetail.setValue('audit', audit, rowID);
			dataDetail.setValue('orderDate', orderDate, rowID);

			dataDetail.setValue('billType', billType, rowID);
//			dataDetail.setValue('direction', direction, rowID);
//			dataDetail.setValue('departmentNo', departmentNo, rowID);
//			dataDetail.setValue('departmentName', departmentName, rowID);
			dataDetail.setValue('employeeNo', employeeNo, rowID);
			dataDetail.setValue('employeeName', employeeName, rowID);
//			dataDetail.setValue('targetNo', targetNo, rowID);
//			dataDetail.setValue('targetName', targetName, rowID);	
			
			dataDetail.setValue('factoryID', factoryID, rowID);	
			dataDetail.setValue('factoryNo', factoryNo, rowID);	
			dataDetail.setValue('factoryName', factoryName, rowID);	

			dataDetail.setValue('customerID', customerID, rowID);
			dataDetail.setValue('customerNo', customerNo, rowID);
			dataDetail.setValue('shortName', shortName, rowID);
			dataDetail.setValue('customerName', customerName, rowID);

			dataDetail.setValue('orderNo', orderNo, rowID);	

			//dataDetail.setValue('serialNo', event.id, rowID);
			dataDetail.setValue('serialNo', serialNo, rowID);

			////////////////////////////////////////////////////////////////////////////////////
			dataDetail.setValue('systemCode', systemCode, rowID);
//			dataDetail.setValue('costingCode', costingCode, rowID);
			dataDetail.setValue('storageTypeD', storageTypeD, rowID);
			dataDetail.setValue('storageTypeDLabel', storageTypeDLabel, rowID);
//			dataDetail.setValue('storageType', storageType, rowID);
//			dataDetail.setValue('storageTypeLabel', storageTypeLabel, rowID);

//			dataDetail.setValue('floorNo', floorNo, rowID);
//			dataDetail.setValue('floorNoD', floorNoD, rowID);
			/////////////////////////////////////////////////////////////////////////////////////////
			

			dataDetail.setValue('billTypeName', billTypeName, rowID);
			
			////////////////////////////////////////////////////////////////////////////////////
//			dataDetail.setValue('revOpay', revOpay, rowID);
			/////////////////////////////////////////////////////////////////////////////////////////
//			dataDetail.setValue('materialType', 2, rowID);	//间接材料
//			dataDetail.setValue('materialTypeLabel', '2.间接材料', rowID);	//间接材料
			
			//更新主表计数器（从表最大流水号）
			var dataMaster = Model.dataMaster;
			var masterRowID = dataMaster.getCurrentID();
			dataMaster.setValue('maxDetailNo', maxDetailNo, masterRowID);	
			
			//更新主表中子表记录数
			dataMaster.setValue('detailsCount', dataMaster.getValue('detailsCount', masterRowID) + 1, masterRowID);	

			dataDetail.setValue('taxType', taxType, rowID);
			dataDetail.setValue('taxTypeLabel', taxTypeLabel, rowID);
			dataDetail.setValue('taxRate', taxRate, rowID);

			dataDetail.setValue('userId', userId, rowID);
			dataDetail.setValue('enterpriseNo', enterpriseNo, rowID);
			dataDetail.setValue('enterpriseName', enterpriseName, rowID);

			dataDetail.setValue('fMasterID',dataDetail.fMasterID,rowID);

		}
		
		Model.dataDetailBeforeSave = function(event) {
			console.log('dataDetailBeforeSave-->',event);
		};
		
		
		Model.dataDetailAfterSave = function(event) {
			console.log('dataDetailAfterSave-->',event);
		}
		
		
		///////////////////按钮组开始///////////////////////////////////////////////////
		//新建
		Model.add = function(){
			
		     var options = {
			         index : 0,
			         defaultValues : [
			             {
			            	 state:'active'
			            	 ,status:'open'
			            	 ,audit:'active'
//			            	 ,orderDate:systemService.getCurrentDate(false)
			            	 ,flowType:1
			            	 ,taxType:1
			            	 ,taxTypeLabel:'1.应税内含'
			            	 ,taxRate:0
			            	 ,depositRate:0
			            	 ,depositAmount:0
			            	 ,pendingAmount:0
			            	 
			            	 ,itemAmount:0
			            	 ,orderAmount:0
			            	 ,orderAmountOld:0
			            	 ,orderAmountTax:0
			            	 ,orderAmountTotal:0
			            	 
			            	 ,discountAmount:0
			            	 ,discountRate:1
			            	 
			            	 ,pickItemIng:0
			            	 ,pickItemAmount:0
			            	 
			            	 ,freightAmount:0
			            	 
			            	 ,isNeedLogistics:0
			            	 ,retailFlag:0
			            	 
			            	 ,actualAmount:0
			            	 ,discountCash:0

			            	 ,itemWeight:0
			            	 ,orderWeight:0
			            	 
			            	 ,resultStatus:'待审核'
				             ,paymentStatus:'unpaid'
					         ,paymentStatusLabel:'待支付'
				            	 
			            	 ,packFlag:0
					         ,orderStatus:'-2'
						     ,orderStatusLabel:'待提交'
				            	 
			            	 ,exchangeRate:0
			            	 ,printTimes:0
			            	 
			            	 ,detailsCount:0
			            	 ,detailsCountState:0
			            	 ,maxDetailNo:0
			            	 
			            	 ,billType: billType
			            	 ,orderDate: ':getCurrentDate()'
				             ,employeeNo: ':getCurrentPsmFID()'
					         ,employeeName: ':getCurrentPsmFName()'
				             ,cUsercode: ':getCurrentPersonCode()'
					         ,cUsername: ':getCurrentPersonName()'
						     ,cDatetime: ':getCurrentDateTime()'
							 ,userId: ':getCurrentPersonID()'
							 ,enterpriseNo: ':getCurrentOgnFID()'
							 ,enterpriseName: ':getCurrentOgnLongName()'
							 ,version: 0

			            }//,
//			             {itemNo:'a2',itemDescribe:'b2'}
			         ]
			     };    

			Model.dataMaster.newData(options);

			if($scope.tabpanel!='single'){
				$scope.tabpanel='single'
			}
		}
		
		//修改
		Model.edit = function(){
			Model.dataMaster.editData();
			if($scope.tabpanel!='single'){
				$scope.tabpanel='single'
			}
		}
		
		//保存
		Model.save = function() {
			Model.dataMaster.saveData();
		}

		//取消编辑
		Model.saveCancel = function() {
			Model.dataMaster.editCancel();
		}
		
		/*
		//不提示直接提交后台删除当前行
		var data = justp.xbl('mainData');
		var deleteConfirm = data.deleteConfirm;
		var directDeleteMode = data.directDeleteMode;
		try{
		    data.deleteConfirm = false;
		    data.directDeleteMode = true;
		    data.deleteData(data.getID());
		}finally{
		    data.deleteConfirm = deleteConfirm;
		    data.directDeleteMode = directDeleteMode;
		}
		*/
		Model.remove = function() {
			/////////////////////////////////////////////////////////////
			/*
			var dataMaster = Model.dataMaster;
			var rowID = dataMaster.getCurrentID();
			var userId = dataMaster.getValue('userId',rowID);
			if(userId!=$rootScope.getCurrentPersonID()){
				systemService.dialogMsg('当前数据不是由您创建，您无权进行此操作！');
				return;
			}
			*/
			////////////////////////////////////////////////////////////////
			Model.dataMaster.deleteData(Model.dataMaster.getCurrentID());
			Model.dataMaster.refreshData();
		};
		
		//刷新
		Model.refresh = function() {
			Model.dataMaster.refreshData();
		}
		
		//打印
		Model.print = function() {
			var options = {};
			options.root = $rootScope.REPORT_URL;
			options.path = $rootScope.path;
			options.id = Model.dataMaster.getCurrentID();
			systemService.openPrintWindow(options); 
		}
		
		//输出：在浏览器窗口打开/下载打印（打印和导出）
		Model.printExport = function() {
			var options = {};
			options.path = $rootScope.getServiceName() + $rootScope.path + "/printPDF";
			options.id = Model.dataMaster.getCurrentID();
			if($rootScope.separation==0){
				//整体项目
				systemService.openPrintExportWindow(options); 
			}else{
				//前后端分离
				systemService.downloadExport(options); 
			}
		};
		
		//下载打印（打印和导出）
//		Model.printExport = function() {
//			var options = {};
//			options.path = $rootScope.getServiceName() + $rootScope.path + '/printPDF';
//			options.id = Model.dataMaster.getCurrentID();
//			systemService.downloadExport(options); 
//		};
		
		//打印WEB
		Model.printWEB = function() {
			var id = Model.dataMaster.getCurrentID();
			var url = "printpl/saleOrder.html?id=" + id + '&serviceName=' + $rootScope.getServiceName() + '&isWithCredentials=true';
			console.log('url-->>',url);
			window.open(url, "_blank");			
		}
		
		///////////////////按钮组结束///////////////////////////////////////////////////
		///////////////////子表按钮组开始///////////////////////////////////////////////////
		//增加
		Model.addrow = function(){
		     var options = {
			         index : Model.dataDetail.getCount(),
			         defaultValues : [
			             {
			            	 itemPrice:0.00
			            	 ,discountRate:1
			            	 ,itemAmount:0
			            	 ,orderAmount:0
			            	 ,orderAmountOld:0
			            	 ,orderAmountTax:0
			            	 ,orderAmountTotal:0
			            	 
			            	 ,pickItemIng:0
			            	 ,pickItemAmount:0
			            	 ,pickPiece:0
			            	 ,backItemIng:0
			            	 ,backItemAmount:0
			            	 ,backPiece:0
			            	 
			            	 ,pendingQuantity:0
			            	 ,pendingPiece:0
			            	 
			            	 ,pieceQuantity:0
			            	 
			            	 ,discountAmount:0
			            	 
			            	 ,handling: -2
			            	 
			            	 ,storeItemAmount:0
			            	 ,piecePackage:0
			            	 ,taxRate:0
			            	 
			            	 ,packFlag:0
					         ,orderStatus:'-2'
						     ,orderStatusLabel:'待提交'
			            	 
			            	 ,frozenFlag:0
			            	 
			            	 ,lv:0
			            	 ,sttts:0
			            	 
			            	 ,itemWeight:0
			            	 ,orderWeight:0
//			            	 ,requirementDate:systemService.getCurrentDate(false)
			            	 
			            }//,
//			             {itemNo:'a2',itemDescribe:'b2'}
			         ]
			     };    

			Model.dataDetail.newData(options);
		}
		
		Model.delrow = function() {
			 if(Model.dataDetail.directDeleteMode){
				//直接删除
				 if(Model.dataDetail.deleteData(Model.dataDetail.getCurrentID())==0){
//					 Model.dataDetail.refreshData();
				 }
			 }else{
				//前台移除
				 if(Model.dataDetail.removeData(Model.dataDetail.getCurrentID())==0){
//					 Model.dataDetail.recordState = 'delete';
				 }
			 }
		};
		///////////////////子表按钮组结束///////////////////////////////////////////////////

		
		//打开对话框（选择工厂）
		Model.triggerFactoryNoClick = function(){
			
     		var dataMaster = Model.dataMaster;
     		var rowID = dataMaster.getCurrentID();
     		var factoryID = dataMaster.getValue('factoryID', rowID);
     		if(factoryID!=null && factoryID!=''){
         		dataMaster.setValue('factoryID', null, rowID);
         		dataMaster.setValue('factoryNo', null, rowID);
         		dataMaster.setValue('factoryName', null, rowID);
     			return;
     		}
			
			var options = {};
			options.recordState = 'none';
			options.id = dataMaster.getValue('enterpriseNo',rowID);

			var modalInstance = systemService.openFactoryNoDialog(options);
	        
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
	             try {
	             	for ( var i = 0; i < returnData.length; i++) {
	             		//alert(returnData[i].rowid+'-->'+returnData[i].billTypeName);

	             		dataMaster.setValue('factoryID', returnData[i].fID, rowID);
	             		dataMaster.setValue('factoryNo', returnData[i].factoryNo, rowID);
	             		dataMaster.setValue('factoryName', returnData[i].factoryName, rowID);
	         			
	                 }
	             } finally {
	             	return;
	             }

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		};
		
		//打开对话框（选择交易对象）
		Model.triggerProviderNoClick = function(){
			
     		var dataMaster = Model.dataMaster;
     		var rowID = dataMaster.getCurrentID();
     		var customerNo = dataMaster.getValue('customerNo', rowID);
     		if(customerNo!=null && customerNo!=''){
         		dataMaster.setValue('storageTypeD', null, rowID);
         		dataMaster.setValue('storageTypeDLabel', null, rowID);
         		dataMaster.setValue('customerID', null, rowID);
         		dataMaster.setValue('customerNo', null, rowID);
         		dataMaster.setValue('shortName', null, rowID);
         		dataMaster.setValue('customerName', null, rowID);
         		
         		dataMaster.setValue('isMember', 0, rowID);
         		dataMaster.setValue('memberNo', null, rowID);
     			
         		dataMaster.setValue('settleCategory', null, rowID);
         		dataMaster.setValue('settleCategoryLabel', null, rowID);
         		dataMaster.setValue('invoiceCategory', null, rowID);
         		dataMaster.setValue('invoiceCategoryLabel', null, rowID);
         		dataMaster.setValue('taxType', 0, rowID);
         		dataMaster.setValue('taxTypeLabel', '0.应税外加', rowID);
         		dataMaster.setValue('taxRate', 0, rowID);
         		dataMaster.setValue('depositRate', 1, rowID);
         		
         		dataMaster.setValue('fAddressName', null, rowID);
         		dataMaster.setValue('fAddress', null, rowID);
         		dataMaster.setValue('fAddressDetail', null, rowID);
         		dataMaster.setValue('fProvince', null, rowID);
         		dataMaster.setValue('fCity', null, rowID);
         		dataMaster.setValue('fZone', null, rowID);
         		dataMaster.setValue('contacts', null, rowID);
         		dataMaster.setValue('mobilePhone', null, rowID);
         		dataMaster.setValue('fPhone', null, rowID);
     			return;
     		}

     		var options = {};
			options.recordState = 'none';
			options.id = dataMaster.getValue('enterpriseNo',rowID);

			var modalInstance = systemService.openCustomerNoDialog(options);
			
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
	             try {
	             	for ( var i = 0; i < returnData.length; i++) {
//	             		console.log(returnData[i]);
	             		dataMaster.setValue('storageTypeD', returnData[i].storageTypeD, rowID);
	             		dataMaster.setValue('storageTypeDLabel', returnData[i].storageTypeDLabel, rowID);
	             		dataMaster.setValue('customerID', returnData[i].fID, rowID);
	             		dataMaster.setValue('customerNo', returnData[i].customerNo, rowID);
	             		dataMaster.setValue('shortName', returnData[i].shortName, rowID);
	             		dataMaster.setValue('customerName', returnData[i].customerName, rowID);
	             		
	             		dataMaster.setValue('isMember', returnData[i].isMember, rowID);
	             		dataMaster.setValue('memberNo', returnData[i].memberNo, rowID);
	         			
	             		dataMaster.setValue('settleCategory', returnData[i].settleCategory, rowID);
	             		dataMaster.setValue('settleCategoryLabel', returnData[i].settleCategoryLabel, rowID);
	             		dataMaster.setValue('invoiceCategory', returnData[i].invoiceCategory, rowID);
	             		dataMaster.setValue('invoiceCategoryLabel', returnData[i].invoiceCategoryLabel, rowID);
	             		dataMaster.setValue('taxType', returnData[i].taxType, rowID);
	             		dataMaster.setValue('taxTypeLabel', returnData[i].taxTypeLabel, rowID);
	             		dataMaster.setValue('taxRate', returnData[i].taxRate, rowID);
	             		dataMaster.setValue('depositRate', returnData[i].depositRate, rowID);
	         			
	             		dataMaster.setValue('fAddressName', returnData[i].fAddressName, rowID);
	             		dataMaster.setValue('fAddress', returnData[i].fAddress, rowID);
	             		dataMaster.setValue('fAddressDetail', returnData[i].fAddressDetail, rowID);
	             		dataMaster.setValue('fProvince', returnData[i].fProvince, rowID);
	             		dataMaster.setValue('fCity', returnData[i].fCity, rowID);
	             		dataMaster.setValue('fZone', returnData[i].fZone, rowID);
	             		dataMaster.setValue('contacts', returnData[i].contacts, rowID);
	             		dataMaster.setValue('mobilePhone', returnData[i].mobilePhone, rowID);
	             		dataMaster.setValue('fPhone', returnData[i].fPhone, rowID);
	                 }
	             } finally {
	             	return;
	             }

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		};
		

		//打开对话框（选择经办人）
		Model.triggerEmployeeNoClick = function(){
			
     		var dataMaster = Model.dataMaster;
     		var rowID = dataMaster.getCurrentID();
     		var employeeNo = dataMaster.getValue('employeeNo', rowID);
     		if(employeeNo!=null && employeeNo!=''){
         		dataMaster.setValue('employeeNo', null, rowID);
         		dataMaster.setValue('employeeName', null, rowID);
     			return;
     		}
			
			
			var options = {};
			options.id = dataMaster.getValue('enterpriseNo',rowID);
			//是否显示人员
			options.psm = true;

			var modalInstance = apiService.openOrgNoDialog(options);
			
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
	             try {
	             	for ( var i = 0; i < returnData.length; i++) {
//	             		alert(returnData[i].sID+'-->'+returnData[i].sFName);
	             		dataMaster.setValue('employeeNo', returnData[i].sFID, rowID);
	             		dataMaster.setValue('employeeName', returnData[i].sFName, rowID);
	         			
	                 }
	             } finally {
	             	return;
	             }

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		};


		//打开对话框（选择地区）
		
		Model.triggerRegionCodeClick = function(){
			
     		var dataMaster = Model.dataMaster;
     		var rowID = dataMaster.getCurrentID();
     		var fAddress = dataMaster.getValue('fAddress', rowID);
     		if(fAddress!=null && fAddress!=''){
         		dataMaster.setValue('fAddress', null, rowID);
         		//dataMaster.setValue('fRegion', null, rowID);
         		dataMaster.setValue('fProvince', null, rowID);
         		dataMaster.setValue('fCity', null, rowID);
         		dataMaster.setValue('fZone', null, rowID);
     			return;
     		}
     		
			//所在地区
			var options = {};
			options.recordState = 'none';
			options.id = dataMaster.getValue('enterpriseNo',rowID);

			var modalInstance = apiService.openRegionCodeDialog(options);
	        
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
	             try {
	             	for ( var i = 0; i < returnData.length; i++) {
	             		//alert(returnData[i].rowid+'-->'+returnData[i].billTypeName);

	             		dataMaster.setValue('fAddress', returnData[i].regionFullName, rowID);
	             		//dataMaster.setValue('fRegion', returnData[i].fRegion, rowID);
	             		dataMaster.setValue('fProvince', returnData[i].fProvince, rowID);
	             		dataMaster.setValue('fCity', returnData[i].fCity, rowID);
	             		dataMaster.setValue('fZone', returnData[i].fZone, rowID);
	                 }
	             } finally {
	             	return;
	             }

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
		};
		

		//打开对话框（选择地址）
		Model.triggerFileAddressClick = function(){
			
     		var dataMaster = Model.dataMaster;
     		var rowID = dataMaster.getCurrentID();
     		/*
     		var fAddress = dataMaster.getValue('fAddress', rowID);
     		if(fAddress!=null && fAddress!=''){
         		dataMaster.setValue('fAddressName', null, rowID);
         		dataMaster.setValue('fAddress', null, rowID);
         		dataMaster.setValue('fAddressDetail', null, rowID);
         		//dataMaster.setValue('fRegion', null, rowID);
         		dataMaster.setValue('fProvince', null, rowID);
         		dataMaster.setValue('fCity', null, rowID);
         		dataMaster.setValue('fZone', null, rowID);
         		dataMaster.setValue('contacts', null, rowID);
         		dataMaster.setValue('mobilePhone', null, rowID);
         		dataMaster.setValue('fPhone', null, rowID);
     			return;
     		}
     		*/
     		
			//地址
			var fMasterID = dataMaster.getValue('customerID', rowID);
			var enterpriseNo = dataMaster.getValue('enterpriseNo', rowID);
			
			var options = {};
			options.recordState = 'none';
			options.id = fMasterID;
			options.enterpriseNo = enterpriseNo;
			
			var modalInstance = systemService.openFileAddressNoDialog(options);
	        
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
	         	
	            try {
	             	for ( var i = 0; i < returnData.length; i++) {
	             		//alert(returnData[i].rowid+'-->'+returnData[i].billTypeName);

	             		dataMaster.setValue('fAddressName', returnData[i].fAddressName, rowID);
	             		dataMaster.setValue('fAddress', returnData[i].fAddress, rowID);
	             		dataMaster.setValue('fAddressDetail', returnData[i].fAddressDetail, rowID);
	             		//dataMaster.setValue('fRegion', returnData[i].fRegion, rowID);
	             		dataMaster.setValue('fProvince', returnData[i].fProvince, rowID);
	             		dataMaster.setValue('fCity', returnData[i].fCity, rowID);
	             		dataMaster.setValue('fZone', returnData[i].fZone, rowID);
	             		dataMaster.setValue('contacts', returnData[i].contacts, rowID);
	             		dataMaster.setValue('mobilePhone', returnData[i].mobilePhone, rowID);
	             		dataMaster.setValue('fPhone', returnData[i].fPhone, rowID);
	         			
	                 }
	             } finally {
	             	return;
	             }
	             
	         	
	         	/*
	         	var addressID = returnData[0].fID;
	         	console.log('addressID-->>',addressID);
	         	//添加地址
				var options = {
						"orderID":rowID,
						"addressID":addressID
				};
				$.ajax({
		            type: "POST",
		            async : true,//异步执行
		            url: $rootScope.getProjectName() + '/sale/saleOrder/single/waybillAddFromAddress',
		            data: JSON.stringify(options),//{'id':rowID,'params':params},//"{}",
		            contentType: "application/json; charset=utf-8",
//		            dataType: "text",
		            dataType: "json",
		            success: function (data) {
		                // Play with returned data in JSON format
		            	console.log('triggerFileAddressClick.data-->>',data);
		            	if(data.code==0){
			            	$rootScope.addAlert('success',data.msg);
			            	Model.dataWaybill.refreshPageData();
			            	$scope.$apply();
		            	}else{
							alert('操作地址错误：'+data.msg);
		            	}
		            }
		        });
	         	 */
	         	

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		};
		
		//整单折扣
		Model.triggerDiscountAmount = function(){
         	var rowID = Model.dataMaster.getCurrentID();
         	console.log('rowID-->>',rowID);
         	var orderAmountTotal = Model.dataMaster.getValue('orderAmountTotal',rowID);
         	
         	var discountAmount = window.prompt("请输入折扣金额：",orderAmountTotal);
         	if(discountAmount==null) return;
         	
         	if (isNaN(discountAmount)){
         		//非数字
             	alert('请输入小于订单金额的数字！');
         	}else{
             	//alert(discountAmount);
         	}
         	
         	if(discountAmount>orderAmountTotal){
             	alert('请输入小于订单金额的数字！');
             	return;
         	}
         	
			var options = {
					"id":rowID,
					"discountAmount":discountAmount
			};
			$.ajax({
	            type: "POST",
	            async : true,//异步执行
	            url: $rootScope.getProjectName() + '/sale/saleOrder/single/discountAmount',
	            data: JSON.stringify(options),//{'id':rowID,'params':params},//"{}",
	            contentType: "application/json; charset=utf-8",
//	            dataType: "text",
	            dataType: "json",
	            success: function (data) {
	                // Play with returned data in JSON format
	            	console.log('Model.triggerDiscountAmount.data-->>',data);
	            	if(data.code==0){
		            	$rootScope.addAlert('success',data.msg);
		            	Model.dataMaster.refreshPageData();
		            	$scope.$apply();
	            	}else{
						alert('打折时发生错误：'+data.msg);
	            	}
	            }
	        });
			
			
		};
		
		
		//打开对话框（追踪运单进展）
		Model.triggerExpressTrack = function(row){
			console.log('Model.triggerExpressTrack.row-->>',row);
			
			var shipperID,waybillNumber;
			
			shipperID = row.shipperNo.value;
			waybillNumber = row.waybillNumber.value;
			
			var options = {};
			
			options.com = shipperID;
			options.nu = waybillNumber;

			var modalInstance = apiService.openExpressTrackDialog(options);
			
		};
		
		

		//打开对话框（选择物料）
		Model.grid_itemNoButtonClick = function(){
			var dataMaster = Model.dataMaster;
			var rowID = dataMaster.getCurrentID();
			var options = {};
			
			options.recordState = 'none';
			options.id = dataMaster.getValue('enterpriseNo',rowID);
			var modalInstance = systemService.openItemNoDialog(options);
			
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	        	
	         	var simpleRow = event.data[0];
	        	systemService.itemSelectSingle(simpleRow,Model.dataDetail);

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		}
		
		//打开多选对话框（选择物料）
		Model.addrows = function(){
			var dataMaster = Model.dataMaster;
			var rowID = dataMaster.getCurrentID();
			var options = {};
			
			options.recordState = 'none';
			options.id = dataMaster.getValue('enterpriseNo',rowID);
			var modalInstance = systemService.openItemNosDialog(options);
			
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
				var returnData = event.data;
		    	for ( var i = 0; i < returnData.length; i++) {
		    		//新增行
		    		Model.addrow();
		    		var simpleRow = returnData[i];
		        	systemService.itemSelectSingle(simpleRow,Model.dataDetail);
		    	}
	        	
	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		}
		
		
		//打开对话框（选择仓库）
		Model.triggerStorageNoClick = function(){
     		var dataMaster = Model.dataMaster;
     		var rowID = dataMaster.getCurrentID();
     		var storageID = dataMaster.getValue('storageID', rowID);
     		if(storageID!=null && storageID!=''){
         		dataMaster.setValue('storageType', null, rowID);
         		dataMaster.setValue('storageTypeLabel', null, rowID);
         		dataMaster.setValue('storageID', null, rowID);
         		dataMaster.setValue('storageNo', null, rowID);
         		dataMaster.setValue('storageName', null, rowID);
         		dataMaster.setValue('floorNo', null, rowID);
     			return;
     		}
     		
			var options = {};
			options.id = dataMaster.getValue('enterpriseNo',rowID);
			options.factoryID = dataMaster.getValue("factoryID",rowID);
			
			var modalInstance = systemService.openStorageListDialog(options);

	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
         		dataMaster.setValue('factoryID', returnData[0].factoryID, rowID);
         		dataMaster.setValue('factoryNo', returnData[0].factoryNo, rowID);
         		dataMaster.setValue('factoryName', returnData[0].factoryName, rowID);

	     		dataMaster.setValue('storageType', returnData[0].storageType, rowID);
	     		dataMaster.setValue('storageTypeLabel', returnData[0].storageTypeLabel, rowID);
	     		dataMaster.setValue('storageID', returnData[0].fID, rowID);
	     		dataMaster.setValue('storageNo', returnData[0].storageNo, rowID);
	     		dataMaster.setValue('storageName', returnData[0].storageName, rowID);
	     		dataMaster.setValue('floorNo', returnData[0].storageFullName, rowID);

	        }, function (reason) {  
	            console.info('用户取消了操作 at: ' + new Date());  
	        });  
			
		};
		
		//打开对话框（选择仓库）
		Model.grid_floorNoButtonClick = function(){

     		var storageID = Model.dataMaster.getValue('storageID', Model.dataMaster.getCurrentID());

     		var dataDetail = Model.dataDetail;
     		var rowID = dataDetail.getCurrentID();
     		
			var options = {};
			options.recordState = 'none';
			options.id = dataDetail.getValue('enterpriseNo',rowID);
			options.factoryID = dataDetail.getValue("factoryID",rowID);
			options.storageID = storageID;
			
			var modalInstance = systemService.openStorageNoDialog(options);

	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
     			dataDetail.setValue('storageType', returnData[0].storageType, rowID);
     			dataDetail.setValue('storageTypeLabel', returnData[0].storageTypeLabel, rowID);
     			dataDetail.setValue('storageID', returnData[0].fID, rowID);
     			dataDetail.setValue('storageNo', returnData[0].storageNo, rowID);
     			dataDetail.setValue('storageName', returnData[0].storageName, rowID);
     			dataDetail.setValue('floorNo', returnData[0].storageFullName, rowID);
     			dataDetail.setValue('allowed', returnData[0].allowed, rowID);

	        }, function (reason) {  
	            console.info('用户取消了操作 at: ' + new Date());  
	        });  
			
		};
		
		
		/////////////////////////////////////////////////////////////////////
		Model.triggerConfirmClick = function(event){
			// 提交单据
			var data = new Object();
			data.bizData = Model.dataMaster;
			data.url = $rootScope.getServiceName() + '/sale/saleOrder/single/confirm';
			var response = systemService.operateBill(data);
		};
		Model.triggerActiveClick = function(event){
			// 撤销提交
			var data = new Object();
			data.bizData = Model.dataMaster;
			data.url = $rootScope.getServiceName() + '/sale/saleOrder/single/active';
			systemService.operateBill(data);
		};
		
		Model.triggerAgreeItClick = function(event){
			// 审核单据
			var data = new Object();
			data.bizData = Model.dataMaster;
			data.url = $rootScope.getServiceName() + '/sale/saleOrder/single/agreeIt';
			systemService.operateBill(data);
		};
		
		Model.triggerUnAgreeClick = function(event){
			// 撤销审核
			var data = new Object();
			data.bizData = Model.dataMaster;
			data.url = $rootScope.getServiceName() + '/sale/saleOrder/single/unAgree';
			systemService.operateBill(data);
		};
		
		Model.triggerCloseClick = function(event){
			// 关闭单据
			var data = new Object();
			data.bizData = Model.dataMaster;
			data.url = $rootScope.getServiceName() + '/sale/saleOrder/single/close';
			systemService.operateBill(data);
		};
		Model.triggerOpenClick = function(event){
			// 撤销审核
			var data = new Object();
			data.bizData = Model.dataMaster;
			data.url = $rootScope.getServiceName() + '/sale/saleOrder/single/open';
			systemService.operateBill(data);
		};

		///////////////////////////////////////////////////////////////////////////////
		
		//双击事件
		Model.gridListRowDblclick = function(rowIndex,rowID){
			$scope.tabpanel = 'single';
		}
		

		/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//		Model.objects = {"dataMaster" : Model.dataMaster,"dataDetail" : Model.dataDetail};
		
		var options = {};
		options.container = Model;
		options.concept = 'SaleOrder';
		options.name = 'dataMaster';
		options.url = $rootScope.path;
		options.httpUrl = $rootScope.getServiceName();
		options.creater = '/sale/saleOrder/single/create';
		options.reader = '/sale/saleOrder/single/query';
		options.writer = '/sale/saleOrder/single/save';
		options.deleter = '/sale/saleOrder/single/delete';
		options.idColumnDefine = "fID";
		options.idColumnName = "fID";
		options.isTree = false;
		options.parentRelation = 'fParent';
		options.nodeKindRelation = 'nodeKind';
		options.nodeLevelRelation = 'nodeLevel';
		options.pathRelation = '';
		options.master = {"data":"","relation":""};
		options.directDeleteMode = true;
		options.limit = 15;
		options.orderBy = "orderNo DESC";

		options.onIndexChanging = null;
		options.onIndexChanged = Model.dataMasterIndexChanged;
		options.onBeforeNew = Model.dataMasterBeforeNew;
		options.onAfterNew = Model.dataMasterAfterNew;
		options.onBeforeDelete = Model.dataMasterBeforeDelete;
		options.onAfterDelete = Model.dataMasterAfterDelete;
		options.onValueChanging = Model.dataMasterValueChanging;
		options.onValueChanged = Model.dataMasterValueChanged;
		options.onDataChanged = Model.dataMasterDataChanged;
		options.onBeforeSave = Model.dataMasterBeforeSave;
		options.onAfterSave = Model.dataMasterAfterSave;
		options.onNewCreateParam = Model.dataMasterNewCreateParam;
		
		Model.dataMaster = new BizData(options);
//		Model.objects.dataMaster = Model.dataMaster;
		//监视对象中的所有变动
		Model.dataMaster.deregRows = $scope.$watch('Model.dataMaster.rows',Model.dataMaster.watchRows,true);//true代表深度监视，包括对象的属性，而不是简单的一个值

		
		
		var options = {};
		options.container = Model;
		options.concept = 'SaleOrderDetail';
		options.name = 'dataDetail';
		options.url = $rootScope.path;
		options.httpUrl = $rootScope.getServiceName();
		options.reader = '/sale/saleOrder/single/queryDetail';
		options.creater = '/sale/saleOrder/single/createDetail';
		options.deleter = '';
		options.idColumnDefine = "fID";
		options.idColumnName = "fID";
		options.isTree = false;
		options.parentRelation = 'fParent';
		options.nodeKindRelation = 'nodeKind';
		options.nodeLevelRelation = 'nodeLevel';
		options.pathRelation = '';
		options.master = {"data":"dataMaster","relation":"fMasterID"};
		options.directDeleteMode = false;
		options.orderBy = 'serialNo ASC';
		

		options.onIndexChanging = null;
		options.onIndexChanged = Model.dataDetailIndexChanged;
		options.onBeforeNew = Model.dataDetailBeforeNew;
		options.onAfterNew = Model.dataDetailAfterNew;
		options.onBeforeDelete = Model.dataDetailBeforeDelete;
		options.onAfterDelete = Model.dataDetailAfterDelete;
		options.onValueChanged = Model.dataDetailValueChanged;
		options.onDataChanged = Model.dataDetailDataChanged;
		options.onBeforeSave = Model.dataDetailBeforeSave;
		options.onAfterSave = Model.dataDetailAfterSave;
		
		Model.dataDetail = new BizData(options);
//		Model.objects.dataDetail = Model.dataDetail;
		//监视对象中的所有变动
		Model.dataDetail.deregRows = $scope.$watch('Model.dataDetail.rows',Model.dataDetail.watchRows,true);//true代表深度监视，包括对象的属性，而不是简单的一个值
		//////////////////////////////////////////////

		///////////////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////////////
		$scope.type = 'EDIT';
		$scope.tabpanel = 'list';

		Model.winParams = $rootScope.winParams;
//		console.log('窗口打开时的参数1',Model.winParams);
		if(Model.winParams!=undefined && Model.winParams!=null && Model.winParams!=''){
			if(Model.winParams.fID){
				Model.dataMaster.id = Model.winParams.fID;
				$scope.tabpanel = 'single';
			}
			//用于在别的单据中点击单号链接时打开此窗口
			if(Model.winParams.billNo){
				//增加过滤器，只显示本人及本公司的数据
				Model.dataMaster.filter = "SaleOrder.billType='" + billType + "'"
				+ " AND SaleOrder.orderNo='" + Model.winParams.billNo + "'"
				;
				$scope.tabpanel = 'single';
//				Model.dataMaster.refreshData();
			}
			//隐藏/显示编辑工具条
			if(Model.winParams.type){
				$scope.type = Model.winParams.type;
			}
		}
		
		Model.dataMaster.refreshData();
		//console.log('Model.dataMaster-->',Model.dataMaster);
		

		///////////////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////////////
		
		
		//生成销售发货单//////////////////////////////////////////////////////////////////
		//激活模态框（好像不需要，指令中统一激活了）
//		$('#invXSFHModal').modal({
//			keyboard: false
//		});
		
		$('#invXSFHModal').on('show.bs.modal', function (event) {
//			console.log('invXSFHModal.show.bs.modal-->',event);
//			  var button = $(event.relatedTarget) // Button that triggered the modal
//			  var recipient = button.data('whatever') // Extract info from data-* attributes
			  // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
			  // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
//			  var modal = $(this)
//			  modal.find('.modal-title').text('New message to ' + recipient)
//			  modal.find('.modal-body input').val(recipient)
			//初始化付款日期
			/*
			$scope.pick = {
				orderDate: systemService.getCurrentDate(false)
			};
			
			var dataMaster = Model.dataMaster;
			var rowID = dataMaster.getCurrentID();
			$scope.pick.billID = rowID;
			$scope.pick.billType = dataMaster.getValue('billType',rowID);
			$scope.pick.billTypeName = dataMaster.getValue('billTypeName',rowID);
			
			$scope.$apply();
			*/
		});
		$('#invXSFHModal').on('hidden.bs.modal', function (event) {
//			console.log('invXSFHModal.hidden.bs.modal-->',event);
			Model.dataMaster.refreshPageData();
			$scope.$apply();
		});
		
		//发货之前
		//打开对话框（选择物流公司）
		Model.triggerShipperNoClick = function(){
     		var dataWaybill = Model.dataWaybill;
     		var rowID = dataWaybill.getCurrentID();
     		var options = {};
			options.recordState = 'none';
			options.id = dataWaybill.getValue('enterpriseNo',rowID);
			var modalInstance=systemService.openShipperNoDialog(options);
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
         		$scope.shipperID = returnData[0].fID;
         		$scope.shipperNo = returnData[0].shipperNo;
         		$scope.shortName = returnData[0].shortName;
         		$scope.shipperName = returnData[0].shipperName;

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
		};
		
		
		//确认发货
		Model.deliveryGoods = function(event){
			var dataWaybill = Model.dataWaybill;
			if(dataWaybill.getCount()<=0){
				//地址不能为空
				alert('物流单据不能为空！');
				return;
			}
			var rowID = dataWaybill.getCurrentID();
   		
    		if($scope.shipperID==null || $scope.shipperID=='' || $scope.waybillNumber==null || $scope.waybillNumber==''){
    			//收货地址不能为空
    			alert('物流公司和运单号不能为空！');
    			return;
    		}
    		
			var r=confirm("确定要发货吗？");
			  if (r==false)
			    {
			    return
			    }
			
    		var options={
            	"id" : rowID,
            	"shipperID" : $scope.shipperID,
            	"shipperNo" : $scope.shipperNo,
            	"shortName" : $scope.shortName,
            	"shipperName" : $scope.shipperName,
            	"waybillNumber" : $scope.waybillNumber,
            	"comments" : $scope.comments,
            };
			
			$.ajax({
	            type: "POST",
	            async : true,//异步（默认），同步为false
	            url: $rootScope.getProjectName() + "/sale/saleOrder/single/deliveryGoods",
	            data: JSON.stringify(options),//{billType:data.billType,ognID:data.ognID},
	            contentType: "application/json; charset=utf-8",
	            dataType: "json",
	            success: function (data) {
	                // Play with returned data in JSON format
//	            	console.log('data->',data);
	            	if(data.code==0){
	        			$('#invXSFHModal').modal('hide');
//		            	alert(data.status + ',单号为：' + data.billNo);
//		    			Model.dataMaster.refreshPageData();
		            	systemService.dialogOpenBill(data);
	            	}else{
//	            		console.log(data);
//	            		console.log(data.status);
	            		data.type = 'danger';
		            	systemService.dialogOpenBill(data);
	            	}
	            },
	            error: function (msg) {
	                alert('ajax调用错误信息：'+msg.responseText);
	            }
	        });
			
			
		};
		
		/////////////////////////////////////////////////////////////////////////////////////

		
		//生成预收款单//////////////////////////////////////////////////////////////////
		
		//会员余额
		$scope.memberAmount = 0;
		
		//选择结算方式
		Model.settleClick = function(row){
			console.log('row-->>',row);
			$scope.settleCode = row.settleCode;
			$scope.settleName = row.settleName;
			console.log('$scope.settleCode-->>',$scope.settleCode);
			console.log('$scope.settleName-->>',$scope.settleName);
			if('Y'==$scope.settleCode){
				//获取会员余额
				//$scope.memberAmount = 0;

				var dataMaster = Model.dataMaster;
				var rowID = dataMaster.getCurrentID();
				var memberNo = dataMaster.getValue('memberNo',rowID);
				var enterpriseNo = dataMaster.getValue('enterpriseNo',rowID);
				
				Model.getMemberAmount(memberNo,enterpriseNo);
			}
		};	


		//获取结算方式
		Model.loadSettleInfoOrg = function(enterpriseNo){
			/*
			var options = {
				"enterpriseNo": enterpriseNo
			}
			*/	
			$.ajax({
				type : "GET",
	        	async : true,//异步加载
				dataType : "json",
	        	contentType: "application/json; charset=utf-8",
				url : $rootScope.getProjectName() + "/baseinfo/settleInfoOrg/getList",  
	        	//data: options,// "{}",
				success : function(data, textStatus, jqXHR) {
					console.log('loadSettleInfoOrg.success.data-->',data);
					if(data.code==0){
						$scope.dataSettleInfoOrg = data.data;
						$scope.$apply();
					}else{
						alert("失败！"+data.status);
					}
			   }
			});
		};
		
		//获取会员信息
		Model.getMemberAmount = function(memberNo,enterpriseNo){
			
			var options = {
					"memberNo": memberNo,
					"enterpriseNo": enterpriseNo
			}
			
			$.ajax({
				type : "GET",
	        	async : true,//异步加载
				dataType : "json",
	        	contentType: "application/json; charset=utf-8",
				url : $rootScope.getProjectName() + "/sale/customer/getMemberAmount",  
	        	data: options,// "{}",
				success : function(data, textStatus, jqXHR) {
					console.log('getMemberAmount.success.data-->',data);
					if(data.code==0){
						//$scope.dataSettleInfoOrg = data.data;
						$scope.memberAmount = data.data.memberAmount;
						$scope.$apply();
					}else{
						alert("失败！"+data.info);
					}
			   }
			});
		};

		//显示
		$('#recYSKDModal').on('show.bs.modal', function (event) {
			//console.log('recYSKDModal.show.bs.modal-->',event);
			$scope.settleCode = 'C';
			$scope.settleName = '现金';
			
			Model.loadSettleInfoOrg();
			$scope.$apply();
		});
		
		//隐藏
		$('#recYSKDModal').on('hidden.bs.modal', function (event) {
//			console.log('recYSKDModal.hidden.bs.modal-->',event);
			$scope.settleCode = 'C';
			$scope.settleName = '现金';

			Model.dataMaster.refreshPageData();
			$scope.$apply();
		});
		
		//准备支付
		Model.readyPay = function () {  
			if($scope.settleCode=='A' || $scope.settleCode=='W'){
				//支付宝或者微信支付，付款码不能为空
				if($scope.authCode==''){
					alert('付款码不能为空！');
					return 'error';
				}
			}
			var dataMaster = Model.dataMaster;
			var rowID = dataMaster.getCurrentID();
			var orderNo = dataMaster.getValue('orderNo',rowID);
			var enterpriseNo = dataMaster.getValue('enterpriseNo',rowID);

			var orderAmountTotal = dataMaster.getValue('orderAmountTotal',rowID);
			var freightAmount = dataMaster.getValue('freightAmount',rowID);
			var discountAmount = dataMaster.getValue('discountAmount',rowID);
			var discountCash = 0;

			
			//计算实际金额
			var orderAmount = orderAmountTotal - discountCash + freightAmount;
			
			var options = {};
			options.orderNo = orderNo;
			options.enterpriseNo = enterpriseNo;
			// options.enterpriseName = $scope.dataOrder.enterpriseName;

			options.settleCategory = $scope.settleCode;
			options.settleCategoryLabel = $scope.settleName;
			options.orderAmount = orderAmount;//实际支付金额
//			options.receiveCashAmount = $scope.receiveCashAmount;
//			options.giveChangeAmount = $scope.receiveCashAmount - orderAmount;
			options.discountCash = discountCash;

			//代金券
			// options.djqaCode = $scope.djqaCode;
			// options.djqaAmount = $scope.djqaAmount;//可以省略

			options.authCode = $scope.authCode;//客户付款码

			return options;
		};

		
		//预收款
		Model.pay = function(event){
//			alert('收款成功！单号：');
			var options = Model.readyPay();
			var dataMaster = Model.dataMaster;
  		
			var response = $.ajax({
	            type: "POST",
	            async : true,//异步（默认），同步为false
	            url: $rootScope.getProjectName() + "/sale/saleOrder/single/receive",
	            data: JSON.stringify(options),//{billType:data.billType,ognID:data.ognID},
	            contentType: "application/json; charset=utf-8",
	            dataType: "json",
	            success: function (data) {
	                // Play with returned data in JSON format
	            	console.log('data->',data);

	            	if(data.code==10000){
	        			$('#recYSKDModal').modal('hide');
	            	}else{
//	            		console.log(data);
	            		alert(data.status);
	            	}
	            },
	            error: function (msg) {
	                alert('ajax调用错误信息：'+msg.responseText);
	            }
	        });
				
			
		};
		
		/////////////////////////////////////////////////////////////////////////////////////
		//出库
		Model.pushXSCK = function(event){
			var r=confirm("确定要生成销售发货单吗？");
			  if (r==false)
			    {
			    return
			    }
			  			
			var dataMaster = Model.dataMaster;
			var rowID = dataMaster.getCurrentID();
			
    		var options={
            	"id" : rowID
            };
			
			var response = $.ajax({
	            type: "POST",
	            async : true,//异步（默认），同步为false
	            url: $rootScope.getProjectName() + "/sale/saleOrder/single/pushXSCK",
	            data: JSON.stringify(options),//{billType:data.billType,ognID:data.ognID},
	            contentType: "application/json; charset=utf-8",
	            dataType: "json",
	            success: function (data) {
	                // Play with returned data in JSON format
	            	console.log('pushXSCK.data->',data);
	            	if(data.code==0){
	        			Model.dataMaster.refreshPageData();
	        			$scope.$apply();
		            	systemService.dialogOpenBill(data);
	            	}else{
//	            		console.log(data);
//	            		console.log(data.status);
	            		data.type = 'danger';
		            	systemService.dialogOpenBill(data);
	            	}
	            }
	        });
			
			
		};
		
		//生成工单//////////////////////////////////////////////////////////////////
		//下达工单：放到物料中心去处理
		
		/////////////////////////////////////////////////////////////////////////////////////

		return Model;
	}	
	
});
	
